package com.tkmybatis.hfy.utils;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.ConnectException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.stereotype.Component;
import lombok.extern.slf4j.Slf4j;
import net.sf.json.JSONObject;

@Slf4j
public class HttpUtil {
	public static final String POST = "POST";
	public static final String GET = "GET";
	
	public static boolean isAjaxRequest(HttpServletRequest request) {
        String requestedWith = request.getHeader("x-requested-with");
        if (requestedWith != null && requestedWith.equalsIgnoreCase("XMLHttpRequest")) {
            return true;
        } else {
            return false;
        }
    }
	
	/**
	 * 发送http请求
	 * @param requestUrl	请求地址
	 * @param requestMethod POST/GET
	 * @return
	 * @throws Exception
	 */
	public static JSONObject httpRequest(String requestUrl, String requestMethod, JSONObject jsObject, JSONObject headObject) throws Exception {  
		log.info("=============="+requestUrl);
        JSONObject jsonObject = null;    
        StringBuffer buffer = new StringBuffer();  
        InputStream inputStream=null;  
        try {  
            URL url = new URL(requestUrl);  
            HttpURLConnection httpUrlConn = (HttpURLConnection) url.openConnection();    
            httpUrlConn.setDoOutput(true);    
            httpUrlConn.setDoInput(true);    
            httpUrlConn.setUseCaches(false);  
            httpUrlConn.setRequestProperty("Content-Length", "0");
            httpUrlConn.setRequestProperty("Content-Type", "application/json");
            httpUrlConn.setConnectTimeout(10000);
            httpUrlConn.setReadTimeout(10000);
            if(headObject != null){
            	Iterator<String> keys = headObject.keys();
            	while (keys.hasNext()) {
            		String key = keys.next();
            		httpUrlConn.setRequestProperty(key, headObject.getString(key));
				}
            }
            // 设置请求方式（GET/POST）    
            httpUrlConn.setRequestMethod(requestMethod);    
            if ("GET".equalsIgnoreCase(requestMethod)) {
            	httpUrlConn.connect(); 
            } else {
            	httpUrlConn.connect();
            	DataOutputStream out = new DataOutputStream(httpUrlConn.getOutputStream());
            	if(jsObject != null) {
            		String content = jsObject.toString();
                	out.write(content.getBytes("UTF-8"));   
            	}
            	//流用完记得关        
            	out.flush();        
            	out.close();
            } 
            //将返回的输入流转换成字符串    
            inputStream = httpUrlConn.getInputStream();    
            InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");    
            BufferedReader bufferedReader = new BufferedReader(inputStreamReader);    
     
            String str = null;    
            while ((str = bufferedReader.readLine()) != null) {    
                buffer.append(str);    
            }    
            bufferedReader.close();    
            inputStreamReader.close();    
            // 释放资源    
            inputStream.close();    
            inputStream = null;    
            httpUrlConn.disconnect();
           log.info("requestUrl="+requestUrl+"返回结果"+buffer.toString());
            jsonObject = JSONObject.fromObject(buffer.toString());  
        } catch (ConnectException ce) {    
              log.error("error:",ce);  
             log.info("=========server connection timed out=======");  
              throw new Exception(ce);
        } catch (Exception e) {    
              log.error("error:",e);  
             log.info("==========http request error===========");  
              throw new Exception(e);
        }finally{  
            try {  
                if(inputStream!=null){  
                    inputStream.close();  
                }  
            } catch (IOException e) {  
                log.error("error:",e);  
            }  
        }   
        return jsonObject;    
    } 
	
	
	private static class DefaultTrustManager implements X509TrustManager {  
        @Override  
        public void checkClientTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {}  
  
        @Override  
        public void checkServerTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {}  
  
        @Override  
        public X509Certificate[] getAcceptedIssuers() {  
            return null;  
        }
  
    } 
	
	/**
	 * 发送https请求
	 * @param requestUrl	请求地址
	 * @param requestMethod POST/GET
	 * @return
	 * @throws Exception
	 */
	public static JSONObject httpsRequest(String requestUrl, String requestMethod, JSONObject jsObject) throws Exception {
		log.info("=============="+requestUrl);
        JSONObject jsonObject = null;
        StringBuffer buffer = new StringBuffer();
        try {
            // 创建SSLContext对象，并使用我们指定的信任管理器初始化
            TrustManager[] tm = { new DefaultTrustManager() };
            SSLContext sslContext = SSLContext.getInstance("TLS");
            sslContext.init(null, tm, new java.security.SecureRandom());
            // 从上述SSLContext对象中得到SSLSocketFactory对象
            SSLSocketFactory ssf = sslContext.getSocketFactory();

            URL url = new URL(null,requestUrl);
            HttpsURLConnection httpUrlConn = (HttpsURLConnection) url.openConnection();
            httpUrlConn.setHostnameVerifier(new HttpUtil().new TrustAnyHostnameVerifier());
            httpUrlConn.setSSLSocketFactory(ssf);

            httpUrlConn.setDoOutput(true);
            httpUrlConn.setDoInput(true);
            httpUrlConn.setUseCaches(false);
            
            httpUrlConn.setRequestProperty("accept", "*/*");
            httpUrlConn.setRequestProperty("connection", "Keep-Alive");
            httpUrlConn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
            // 设置请求方式（GET/POST）
            httpUrlConn.setRequestMethod(requestMethod);
            if ("GET".equalsIgnoreCase(requestMethod)) {
            	httpUrlConn.connect();
            }else {
            	httpUrlConn.connect();
            	DataOutputStream out = new DataOutputStream(httpUrlConn.getOutputStream());
            	String content = jsObject.toString();
            	out.write(content.getBytes("UTF-8"));        
            	//流用完记得关        
            	out.flush();        
            	out.close();
            }
            // 将返回的输入流转换成字符串
            InputStream inputStream = httpUrlConn.getInputStream();
            InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
            BufferedReader bufferedReader = new BufferedReader(inputStreamReader);

            String str = null;
            while ((str = bufferedReader.readLine()) != null) {
                buffer.append(str);
            }
            bufferedReader.close();
            inputStreamReader.close();
            // 释放资源
            inputStream.close();
            inputStream = null;
            httpUrlConn.disconnect();
            jsonObject = JSONObject.fromObject(buffer.toString());
        } catch (ConnectException ce) {
        	log.error("error:",ce); 
        	log.info("=========server connection timed out=======");  
            throw new Exception(ce);
        } catch (Exception e) {
        	log.error("error:",e);
        	log.info("==========http request error===========");  
            throw new Exception(e);
        }
        return jsonObject;
    }
	
	
	public static JSONObject httpsRequest(String requestUrl, String requestMethod) throws Exception {
        return httpsRequest(requestUrl, requestMethod, null);
    }
	
	public class TrustAnyHostnameVerifier implements HostnameVerifier {
		public boolean verify(String hostname, SSLSession session) {
			// 直接返回true
		  return true;
	  	}
	}
	
	
	/**
	 * 获取IP地址
	 * @param request
	 * @return
	 */
	public static String getRemortIp(HttpServletRequest request){
	    String ip = request.getHeader("x-forwarded-for");  
        if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {  
            ip = request.getHeader("Proxy-Client-IP");  
        }  
        if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {  
            ip = request.getHeader("WL-Proxy-Client-IP");  
        }  
        if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {  
            ip = request.getRemoteAddr();  
        }  
        return ip;  
	}

	public static String getBasePath(HttpServletRequest request){
		String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+request.getContextPath()+"/"; 
		return basePath;
	}
	
	public static String mapToUrl(String baseUrl, Map<String,String> paramMap) {
        String params = "";
        for(String s : paramMap.keySet()){
            params += s+"="+paramMap.get(s) + "&";
        }
        if(params.length() > 0) {
            params = params.substring(0, params.length()-1);
        }
        return baseUrl + "?" + params;
    }
	
	public static String getToken(HttpServletRequest request) {
	    String token = request.getHeader("access_token");
    	if(StringUtils.isBlank(token)) {
    		token = request.getParameter("access_token");
    	}
    	return token; 
	}
	
	
	public static void downLoad(OutputStream out, String fileName, HttpServletResponse response, HttpServletRequest request, HSSFWorkbook wb) throws Exception{
		//下载
		response.reset();
		String excelFieldName = "";
		if (request.getHeader("User-Agent").toUpperCase().indexOf("MSIE") > -1) {// IE
			excelFieldName = URLEncoder.encode(fileName, "UTF8");
		} else if (request.getHeader("User-Agent").toUpperCase().indexOf("CHROME") > -1) {// CHROME
			excelFieldName = URLEncoder.encode(fileName, "UTF8");
		} else {
			excelFieldName = new String(fileName.replaceAll(" ", "").getBytes("UTF-8"), "ISO8859-1");
		}
		response.addHeader("Content-Disposition", "attachment;filename=" + excelFieldName + ".xls");
		response.setContentType("application/vnd.ms-excel;charset=utf-8");
		wb.write(out);
	}
}
